package com.wzs.example.provider;
import com.wzs.example.common.service.UserService;
import com.wzs.rpc.RpcApplication;
import com.wzs.rpc.config.RegistryConfig;
import com.wzs.rpc.config.RpcConfig;
import com.wzs.rpc.constant.RpcConstant;
import com.wzs.rpc.model.ServiceMetaInfo;
import com.wzs.rpc.registry.LocalRegistry;
import com.wzs.rpc.registry.Registry;
import com.wzs.rpc.registry.RegistryFactory;
import com.wzs.rpc.server.HttpServer;
import com.wzs.rpc.server.VertxHttpServer;
import com.wzs.rpc.server.tcp.VertxTcpServer;

public class EasyProviderExample {
    public static void main(String[] args){
        //本地注册服务（因为Handler要根据request中的服务名找到对应的服务实例）
        LocalRegistry.register(UserService.class.getName(), UserServiceImpl.class);

        //使用注册中心
        //1.加载RpcConfig
        RpcConfig rpcConfig = RpcApplication.getRpcConfig();
        //2.连接配置中心
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig, true);
        //创建并注册Shutdown Hook,JVM退出时执行destroy操作
        Runtime.getRuntime().addShutdownHook(new Thread(registry::destroy));
        //3.注册服务
        ServiceMetaInfo serviceMetaInfo = ServiceMetaInfo.builder()
                .serviceName(UserService.class.getName())
                .serviceVersion(RpcConstant.DEFAULT_SERVICE_VERSION)
                .serviceHost(rpcConfig.getServerHost())
                .servicePort(rpcConfig.getServerPort())
                .build();
        try {
            registry.register(serviceMetaInfo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //启动web服务
        HttpServer httpServer = new VertxTcpServer();
        httpServer.doStart(rpcConfig.getServerPort());
    }
}
